<template>
  <div class="comment-photo">
    <img :src="img" alt="" class="img" ref="img">

    <div class="toolbar">
        <div class="cancel" @click="$emit('close')">取消</div>
        <div class="confirm" @click="confirm">保存</div>
    </div>
  </div>
</template>

<script>
import 'cropperjs/dist/cropper.css'
import Cropper from 'cropperjs'
import {updatePhoto} from '@/api/user'
export default {
    name:'commentPhoto',
    props:{
        img:{
            type:[String,Object],
            required:true
        }
    },
    data() {
        return {
            cropper:null
        }
    },
    mounted(){
        const image = this.$refs.img
        this.cropper = new Cropper(image,{
            viewMode:1,
            dragMode:'move',
            aspectRatio:1,
            autoCropArea:1,
            // cropBoxMovable:false,
            // cropBoxResizable:false,
            background:false,
            movable:true
        })
    },
    methods:{
        confirm(){
            this.cropper.getCroppedCanvas().toBlob( (blob)=>{
                this.updatePhotoFn(blob)
            })
        },
        async updatePhotoFn(blob){
                this.$toast.loading({
                    message:'保存中...',
                    forbidClick:true, //禁止背景点击
                    duration:0 //持续展示
                })
                try{
                    //接口为content-Type 是 application/json
                    // updatePhoto({
                    //     photo:blob
                    // })
                    //接口为content-Type 是 multipart/form-data
                        //传FormData对象
                const formData = new FormData()
                formData.append('photo',blob)

                const {data} = await updatePhoto(formData)

                //关闭弹出层
                this.$emit('close')
                //更新视图
                this.$emit('upPhoto',data.data.photo)
                //更新提示
                this.$toast.success('更新头像成功')
                }catch(err){
                    this.$toast.fail('更新头像失败')
                }
              
        }
    }

}
</script>

<style lang="less" scoped>
    .comment-photo{
        background-color: rgb(187, 223, 235);
        height: 100%;
        .img{
            display: block;
            max-width: 100%;
        }
        .toolbar{
            position: fixed;
            left: 0;
            right: 0;
            bottom: 0;
            display: flex;
            justify-content: space-between;
            .cancel,.confirm{
                width: 90px;
                height: 90px;
                font-size: 36px;
                display: flex;
                justify-content: center;
                align-items: center;
                color: rgb(236, 123, 123)
            }
        }
    }
</style>